package com.mkjli.ScheduleManager.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mkjli.ScheduleManager.bo.ScheduleBO;
import com.mkjli.ScheduleManager.model.TaskModel;

/**
 * Handles requests for the application home page.
 */
@Controller
public class ScheduleController {

	private static final Logger logger = LoggerFactory.getLogger(ScheduleController.class);

	@Autowired
	private ScheduleBO scheduleBO;

	@RequestMapping("/index")
	public ModelAndView index(String year, String month, Locale locale) throws ParseException {
		Date today = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		String todayStr = sdf.format(today);
		if (year == null) {
			year = todayStr.substring(0, 4);
		}
		if (month == null) {
			month = todayStr.substring(4, 6);
		}
		Calendar calendar = new GregorianCalendar(locale);
		calendar.set(Integer.parseInt(year), Integer.parseInt(month) - 1, 1);
		calendar.add(Calendar.DATE, -1 * calendar.get(Calendar.DAY_OF_WEEK));

		ModelAndView modelAndView = new ModelAndView("schedule/main");
		Map<String, String> calendarData = scheduleBO.getCalendarData(year, month);

		calendar.set(Integer.parseInt(year), Integer.parseInt(month) - 1, 1);
		calendar.add(Calendar.MONTH, -1);
		calendarData.put("prevYear", Integer.toString(calendar.get(Calendar.YEAR)));
		calendarData.put("prevMonth", Integer.toString(calendar.get(Calendar.MONTH) + 1));
		calendar.add(Calendar.MONTH, 2);
		calendarData.put("nextYear", Integer.toString(calendar.get(Calendar.YEAR)));
		calendarData.put("nextMonth", Integer.toString(calendar.get(Calendar.MONTH) + 1));
		modelAndView.addObject("calendarData", calendarData);
		modelAndView.addObject("scheduleData", scheduleBO.getScheduleData(calendarData));

		return modelAndView;
	}

	@RequestMapping("/insertTask")
	@ResponseBody
	public String insertTask(TaskModel task) {
		String id;
		try {
			scheduleBO.insertTask(task);
			TaskModel last = scheduleBO.selectLastTask();
			id = last.getId();
		} catch (Exception e) {
			logger.error("insert error", e);
			id = "-1";
		}
		return id;
	}

	@RequestMapping("/updateTask")
	@ResponseBody
	public String updateTask(TaskModel task) {
		try {
			scheduleBO.updateTask(task);
		} catch (Exception e) {
			return "-1";
		}
		return task.getId();
	}
}
